<?php
// +----------------------------------------------------------------------
// | 通用PHP框架 [ ThinkPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 郑州智众 [Paulxun@qq.com]
// +----------------------------------------------------------------------
// | 官方网站: https://www.zzmind.com
// +----------------------------------------------------------------------

namespace app\user\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\user\model\Member as MemberModel;
use app\user\model\Vip as VipModel;
use app\user\model\Rebate as RebateModel;
use app\user\model\Level;
use util\Tree;
use think\facade\Db;

/**
 * Vip会员管理控制器
 * @package app\user\admin
 */
class Rebate extends Admin
{
    /**
     * 用户首页
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index($uid = 0)
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
		
		if ($uid > 0) {
			$map[] = ['uid', '=', $uid];
			$search_field = [];
		} else {
			$search_field = ['member_id' => '会员ID',  'user_vip.realname' => '姓名', 'user_vip.mobile' => '手机号'];
		}
		// 排序条件
		$order = $this->getOrder('user_rebate.create_time desc');
		
        // 数据列表
        $data_list = RebateModel::getList($map, $order);
		
		// 来源按钮
		$btn_view = [
			'title' => '查看来源',
			'icon'  => 'fa fa-fw fa-eye',
			'class' => 'btn btn-xs btn-primary',
			'href'  => url('view', ['id' => '__id__'])
		];
		
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('Vip管理') // 设置页面标题
            ->setSearch($search_field) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['uid', '会员ID'],
                ['realname', '姓名'],
                ['mobile', '手机号'],
				['group', '会员等级', 'callback', function($value){return Level::level_list($value);}],
				['model', '返佣方式', 'status', '', RebateModel::model()],
				['money', '返佣金额', 'callback', function($value){return '￥'. $value / 100 ;}],
				['pre', '返佣比例', 'callback', function($value){return $value .'%';}],
				['money_take', '返佣余额', 'callback', function($value){return '￥'. $value / 100 ;}],
				['from_uid', '来源用户', 'callback', function($value){$info = VipModel::info($value);  return isset($info['realname']) ? $info['realname'] : '未知';}],
                ['create_time', '时间', 'datetime'],
                ['right_button', '操作', 'btn']
            ])
            ->setRowList($data_list) // 设置表格数据
			->addRightButton('custom', $btn_view, true)
			->addFilterList('group', Level::level_list())
			->addFilterList('model', RebateModel::model())
			->addTimeFilter('user_rebate.create_time')
            ->fetch(); // 渲染页面
    }
    /**
     * 查看来源
     * @param null $id 返佣id
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function view($id = null)
    {
        if ($id === null) $this->error('缺少参数');

        $rebate = RebateModel::find($id);
		if (!$rebate) $this->error('未找到该记录');
		
		$info = VipModel::info($rebate['from_uid']);
		
		if (!$info) $this->error('来源用户不存在');
		
		switch ($rebate['model']) {
			case 1 :
			$url = url('user/money/index', ['id' => $rebate['oid'], '_pop' => 1]);
			break;
			case 2 :
			$url = url('mall/order/detail', ['id' => $rebate['oid'], '_pop' => 1]);
			break;
			default:
			$url = url('user/moneytake/index', ['id' => $rebate['oid'], '_pop' => 1]);
		}
		$this->redirect($url);
    }
	
    /**
     * 会员充值
     * @param null $id 用户id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function pay($id = null)
    {
        if ($id === null) $this->error('缺少参数');
    
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
    
            // 验证
            if(!is_numeric($data['pay']) || $data['pay'] == 0) $this->error('充值金额必须为非0数字');
			$money = 0;
			$money_se = 0;
			if ($data['type'] == 1) {
				$money = $data['pay'] * 100;
			} else {
				$money_se = $data['pay'] * 100;
			}
			$credit = MoneyModel::moneyLog($data['member_id'], 1, $money, $money_se, 0, $data['remark']);
            if ($credit !== false) {
				// 处理返佣
				$rebate = new RebateModel;
				$rebate->saveData($id, 1, $data['type'], $data['pay'] * 100, $credit);
                // 记录行为
                $this->success('充值成功', null, '_close_pop');
            } else {
                $this->error($credit, null, '_close_pop');
            }
        }
		
		
        // 获取数据
        $info = VipModel::where('member_id', $id)->find();
		
		$info['money'] = $info['money'] / 100 ;
		$info['money_se'] = $info['money_se'] / 100 ;
		// $user = new VipModel;
		// dd($user->getFathers($info['pid']));
    
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'member_id'],
				['static', 'member_id', '会员ID', ''],
                ['static', 'realname', '真实姓名', ''],
				['static', 'mobile', '手机号'],
				['static', 'money', '余额', '单位：元'],
				['static', 'money_se', '补货余额', '单位：元'],
				['text:8', 'pay', '充值金额', '','', ['<i class="fa fa-fw fa-yen"></i>', '元']],
				['radio', 'type', '充值类型', '首单余额及补货余额，购买商品折扣不同，并将按照不同比例返点', [1 =>'首单余额', 2=>'补货余额'], 1],
				['text:8', 'remark', '备注',]
            ])
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }   
    
    /**
     * 删除Vip用户
     * @param array $ids 用户id
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete($ids = [])
    {
        return $this->setStatus('delete');
    }

    /**
     * 启用用户
     * @param array $ids 用户id
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function enable($ids = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用用户
     * @param array $ids 用户id
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function disable($ids = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置产品状态：删除、禁用、启用
     * @param string $type 类型：enable/disable
     * @param array $record
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setStatus($type = '', $record = [])
    {
        $ids        = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $realname = VipModel::where('member_id', 'in', $ids)->column('realname');
        return parent::setStatus($type, ['vip_'.$type, 'user_vip', 0, UID, implode('、', $realname)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id      = input('post.pk', '');
        $field   = input('post.name', '');
        $value   = input('post.value', '');

        $config  = VipModel::where('member_id', $id)->value($field);
		cache('vip_'. $id, $result);
        $details = '字段(' . $field . ')，原值(' . $config . ')，新值：(' . $value . ')';
        return parent::quickEdit(['member_edit', 'user_member', $id, UID, $details]);
    }
}
